package com.jietuo.class01;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2024/3/1
 * @description: 5，在一个有序数组中，找>=某个数最左侧的位置
 */
public class Code05_BSNearLeft {

    public static void main(String[] args) {
        int target = 10;
        int[] arr = new int[]{1,2,5,8,10,13,15};
        int position = getPosition(arr, target);
        System.out.println(position);
    }

    /**
     * 有序数组，采用二分查找的方式，只要是>= 目标值，则向前继续二分
     *
     * @param arr    有序数组
     * @param target 目标
     * @return 位置
     */
    public static int getPosition(int[] arr, int target) {
        int left = 0;
        int right = arr.length -1;
        int targetPosition = 0;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (arr[mid] >= target) {
                right = mid - 1;
                targetPosition = mid;
            } else {
                left = mid + 1;
            }
        }
        return targetPosition;
    }
}
